using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AudioManager : MonoBehaviour
{
    [Header("音频源设置")]
    public AudioSource musicSource;
    public AudioSource sfxSource;
    public AudioSource uiSource;
    
    [Header("背景音乐")]
    public AudioClip menuMusic;
    public AudioClip gameMusic;
    public AudioClip bossMusic;
    public AudioClip victoryMusic;
    public AudioClip gameOverMusic;
    
    [Header("音效")]
    public AudioClip playerShootSFX;
    public AudioClip enemyShootSFX;
    public AudioClip explosionSFX;
    public AudioClip hitSFX;
    public AudioClip powerUpCollectSFX;
    public AudioClip shieldActivateSFX;
    public AudioClip screenClearSFX;
    public AudioClip enemyDeathSFX;
    public AudioClip playerHitSFX;
    public AudioClip waveCompleteSFX;
    
    [Header("UI音效")]
    public AudioClip buttonClickSFX;
    public AudioClip buttonHoverSFX;
    public AudioClip menuSelectSFX;
    public AudioClip pauseSFX;
    public AudioClip resumeSFX;
    
    [Header("音量设置")]
    [Range(0f, 1f)] public float masterVolume = 1f;
    [Range(0f, 1f)] public float musicVolume = 0.7f;
    [Range(0f, 1f)] public float sfxVolume = 0.8f;
    [Range(0f, 1f)] public float uiVolume = 0.6f;
    
    [Header("音频设置")]
    public bool enableMusic = true;
    public bool enableSFX = true;
    public bool enableUI = true;
    public bool fadeTransitions = true;
    public float fadeInDuration = 1f;
    public float fadeOutDuration = 0.5f;
    
    [Header("3D音效设置")]
    public float maxDistance = 20f;
    public float minDistance = 1f;
    public AnimationCurve distanceCurve = AnimationCurve.Linear(0, 1, 1, 0);
    
    [Header("调试设置")]
    public bool showDebugInfo = true;
    
    // 单例模式
    public static AudioManager Instance { get; private set; }
    
    // 音频池
    private Dictionary<string, AudioClip> audioClips;
    private List<AudioSource> sfxPool;
    private int maxSFXSources = 10;
    
    // 当前播放状态
    private AudioClip currentMusic;
    private Coroutine musicFadeCoroutine;
    
    void Awake()
    {
        // 单例模式实现
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
            InitializeAudioManager();
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    void InitializeAudioManager()
    {
        // 创建音频源
        if (musicSource == null)
        {
            GameObject musicObj = new GameObject("MusicSource");
            musicObj.transform.SetParent(transform);
            musicSource = musicObj.AddComponent<AudioSource>();
            musicSource.loop = true;
            musicSource.playOnAwake = false;
        }
        
        if (sfxSource == null)
        {
            GameObject sfxObj = new GameObject("SFXSource");
            sfxObj.transform.SetParent(transform);
            sfxSource = sfxObj.AddComponent<AudioSource>();
            sfxSource.loop = false;
            sfxSource.playOnAwake = false;
        }
        
        if (uiSource == null)
        {
            GameObject uiObj = new GameObject("UISource");
            uiObj.transform.SetParent(transform);
            uiSource = uiObj.AddComponent<AudioSource>();
            uiSource.loop = false;
            uiSource.playOnAwake = false;
        }
        
        // 初始化音频池
        InitializeAudioPool();
        
        // 创建默认音频剪辑
        CreateDefaultAudioClips();
        
        // 应用音量设置
        UpdateVolumeSettings();
        
        Debug.Log("音频管理器已初始化");
    }
    
    void InitializeAudioPool()
    {
        sfxPool = new List<AudioSource>();
        
        for (int i = 0; i < maxSFXSources; i++)
        {
            GameObject sfxObj = new GameObject($"SFXPool_{i}");
            sfxObj.transform.SetParent(transform);
            AudioSource source = sfxObj.AddComponent<AudioSource>();
            source.loop = false;
            source.playOnAwake = false;
            source.volume = sfxVolume * masterVolume;
            sfxPool.Add(source);
        }
        
        Debug.Log($"音效池已创建，包含{maxSFXSources}个音频源");
    }
    
    void CreateDefaultAudioClips()
    {
        audioClips = new Dictionary<string, AudioClip>();
        
        // 如果没有提供音频剪辑，创建默认的（程序生成的音效）
        if (playerShootSFX == null)
        {
            playerShootSFX = CreateSyntheticSound("PlayerShoot", 0.1f, 800f);
        }
        
        if (enemyShootSFX == null)
        {
            enemyShootSFX = CreateSyntheticSound("EnemyShoot", 0.15f, 600f);
        }
        
        if (explosionSFX == null)
        {
            explosionSFX = CreateSyntheticSound("Explosion", 0.3f, 200f);
        }
        
        if (hitSFX == null)
        {
            hitSFX = CreateSyntheticSound("Hit", 0.1f, 1000f);
        }
        
        if (powerUpCollectSFX == null)
        {
            powerUpCollectSFX = CreateSyntheticSound("PowerUp", 0.2f, 1200f);
        }
        
        if (buttonClickSFX == null)
        {
            buttonClickSFX = CreateSyntheticSound("ButtonClick", 0.1f, 1500f);
        }
        
        // 将音频剪辑添加到字典中
        audioClips["PlayerShoot"] = playerShootSFX;
        audioClips["EnemyShoot"] = enemyShootSFX;
        audioClips["Explosion"] = explosionSFX;
        audioClips["Hit"] = hitSFX;
        audioClips["PowerUpCollect"] = powerUpCollectSFX;
        audioClips["ButtonClick"] = buttonClickSFX;
        
        Debug.Log("默认音频剪辑已创建");
    }
    
    AudioClip CreateSyntheticSound(string name, float duration, float frequency)
    {
        int sampleRate = 44100;
        int samples = Mathf.RoundToInt(duration * sampleRate);
        float[] audioData = new float[samples];
        
        for (int i = 0; i < samples; i++)
        {
            float time = (float)i / sampleRate;
            float wave = Mathf.Sin(2 * Mathf.PI * frequency * time);
            
            // 添加包络以避免爆音
            float envelope = 1f;
            if (time < 0.01f)
            {
                envelope = time / 0.01f; // 淡入
            }
            else if (time > duration - 0.01f)
            {
                envelope = (duration - time) / 0.01f; // 淡出
            }
            
            audioData[i] = wave * envelope * 0.5f;
        }
        
        AudioClip clip = AudioClip.Create(name, samples, 1, sampleRate, false);
        clip.SetData(audioData, 0);
        
        return clip;
    }
    
    void UpdateVolumeSettings()
    {
        if (musicSource != null)
        {
            musicSource.volume = musicVolume * masterVolume;
        }
        
        if (sfxSource != null)
        {
            sfxSource.volume = sfxVolume * masterVolume;
        }
        
        if (uiSource != null)
        {
            uiSource.volume = uiVolume * masterVolume;
        }
        
        // 更新音效池中的音量
        foreach (var source in sfxPool)
        {
            source.volume = sfxVolume * masterVolume;
        }
    }
    
    // 公共方法：播放背景音乐
    public void PlayMusic(AudioClip clip, bool loop = true, bool fade = true)
    {
        if (!enableMusic || clip == null) return;
        
        if (currentMusic == clip && musicSource.isPlaying) return;
        
        currentMusic = clip;
        
        if (fade && fadeTransitions)
        {
            if (musicFadeCoroutine != null)
            {
                StopCoroutine(musicFadeCoroutine);
            }
            musicFadeCoroutine = StartCoroutine(FadeMusicCoroutine(clip, loop));
        }
        else
        {
            musicSource.clip = clip;
            musicSource.loop = loop;
            musicSource.Play();
        }
        
        if (showDebugInfo)
        {
            Debug.Log($"播放背景音乐: {clip.name}");
        }
    }
    
    IEnumerator FadeMusicCoroutine(AudioClip newClip, bool loop)
    {
        // 淡出当前音乐
        if (musicSource.isPlaying)
        {
            float startVolume = musicSource.volume;
            float elapsed = 0f;
            
            while (elapsed < fadeOutDuration)
            {
                elapsed += Time.unscaledDeltaTime;
                musicSource.volume = Mathf.Lerp(startVolume, 0f, elapsed / fadeOutDuration);
                yield return null;
            }
            
            musicSource.Stop();
        }
        
        // 设置新音乐
        musicSource.clip = newClip;
        musicSource.loop = loop;
        musicSource.volume = 0f;
        musicSource.Play();
        
        // 淡入新音乐
        float targetVolume = musicVolume * masterVolume;
        float elapsed2 = 0f;
        
        while (elapsed2 < fadeInDuration)
        {
            elapsed2 += Time.unscaledDeltaTime;
            musicSource.volume = Mathf.Lerp(0f, targetVolume, elapsed2 / fadeInDuration);
            yield return null;
        }
        
        musicSource.volume = targetVolume;
    }
    
    // 公共方法：停止背景音乐
    public void StopMusic(bool fade = true)
    {
        if (fade && fadeTransitions)
        {
            if (musicFadeCoroutine != null)
            {
                StopCoroutine(musicFadeCoroutine);
            }
            musicFadeCoroutine = StartCoroutine(FadeOutMusicCoroutine());
        }
        else
        {
            musicSource.Stop();
        }
        
        currentMusic = null;
    }
    
    IEnumerator FadeOutMusicCoroutine()
    {
        float startVolume = musicSource.volume;
        float elapsed = 0f;
        
        while (elapsed < fadeOutDuration)
        {
            elapsed += Time.unscaledDeltaTime;
            musicSource.volume = Mathf.Lerp(startVolume, 0f, elapsed / fadeOutDuration);
            yield return null;
        }
        
        musicSource.Stop();
        musicSource.volume = musicVolume * masterVolume;
    }
    
    // 公共方法：播放音效
    public void PlaySFX(AudioClip clip, float volume = 1f, float pitch = 1f)
    {
        if (!enableSFX || clip == null) return;
        
        AudioSource availableSource = GetAvailableSFXSource();
        if (availableSource != null)
        {
            availableSource.clip = clip;
            availableSource.volume = sfxVolume * masterVolume * volume;
            availableSource.pitch = pitch;
            availableSource.Play();
            
            if (showDebugInfo)
            {
                Debug.Log($"播放音效: {clip.name}");
            }
        }
    }
    
    // 公共方法：播放3D音效
    public void PlaySFX3D(AudioClip clip, Vector3 position, float volume = 1f, float pitch = 1f)
    {
        if (!enableSFX || clip == null) return;
        
        AudioSource availableSource = GetAvailableSFXSource();
        if (availableSource != null)
        {
            availableSource.transform.position = position;
            availableSource.clip = clip;
            availableSource.volume = sfxVolume * masterVolume * volume;
            availableSource.pitch = pitch;
            availableSource.spatialBlend = 1f; // 3D音效
            availableSource.rolloffMode = AudioRolloffMode.Custom;
            availableSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, distanceCurve);
            availableSource.maxDistance = maxDistance;
            availableSource.minDistance = minDistance;
            availableSource.Play();
        }
    }
    
    // 公共方法：播放UI音效
    public void PlayUISFX(AudioClip clip, float volume = 1f)
    {
        if (!enableUI || clip == null) return;
        
        uiSource.clip = clip;
        uiSource.volume = uiVolume * masterVolume * volume;
        uiSource.Play();
    }
    
    AudioSource GetAvailableSFXSource()
    {
        // 寻找空闲的音频源
        foreach (var source in sfxPool)
        {
            if (!source.isPlaying)
            {
                source.spatialBlend = 0f; // 重置为2D音效
                return source;
            }
        }
        
        // 如果没有空闲的，使用主音效源
        return sfxSource;
    }
    
    // 公共方法：播放预定义音效
    public void PlayPlayerShoot() => PlaySFX(playerShootSFX);
    public void PlayEnemyShoot() => PlaySFX(enemyShootSFX);
    public void PlayExplosion(Vector3 position) => PlaySFX3D(explosionSFX, position);
    public void PlayHit() => PlaySFX(hitSFX);
    public void PlayPowerUpCollect() => PlaySFX(powerUpCollectSFX);
    public void PlayShieldActivate() => PlaySFX(shieldActivateSFX);
    public void PlayScreenClear() => PlaySFX(screenClearSFX);
    public void PlayEnemyDeath(Vector3 position) => PlaySFX3D(enemyDeathSFX, position);
    public void PlayPlayerHit() => PlaySFX(playerHitSFX);
    public void PlayWaveComplete() => PlaySFX(waveCompleteSFX);
    public void PlayButtonClick() => PlayUISFX(buttonClickSFX);
    public void PlayButtonHover() => PlayUISFX(buttonHoverSFX);
    public void PlayMenuSelect() => PlayUISFX(menuSelectSFX);
    public void PlayPause() => PlayUISFX(pauseSFX);
    public void PlayResume() => PlayUISFX(resumeSFX);
    
    // 公共方法：播放游戏状态音乐
    public void PlayMenuMusic() => PlayMusic(menuMusic);
    public void PlayGameMusic() => PlayMusic(gameMusic);
    public void PlayBossMusic() => PlayMusic(bossMusic);
    public void PlayVictoryMusic() => PlayMusic(victoryMusic, false);
    public void PlayGameOverMusic() => PlayMusic(gameOverMusic, false);
    
    // 公共方法：设置音量
    public void SetMasterVolume(float volume)
    {
        masterVolume = Mathf.Clamp01(volume);
        UpdateVolumeSettings();
    }
    
    public void SetMusicVolume(float volume)
    {
        musicVolume = Mathf.Clamp01(volume);
        UpdateVolumeSettings();
    }
    
    public void SetSFXVolume(float volume)
    {
        sfxVolume = Mathf.Clamp01(volume);
        UpdateVolumeSettings();
    }
    
    public void SetUIVolume(float volume)
    {
        uiVolume = Mathf.Clamp01(volume);
        UpdateVolumeSettings();
    }
    
    // 公共方法：切换音频开关
    public void ToggleMusic()
    {
        enableMusic = !enableMusic;
        if (!enableMusic)
        {
            StopMusic();
        }
    }
    
    public void ToggleSFX()
    {
        enableSFX = !enableSFX;
    }
    
    public void ToggleUI()
    {
        enableUI = !enableUI;
    }
    
    // 公共方法：暂停/恢复所有音频
    public void PauseAllAudio()
    {
        musicSource.Pause();
        
        foreach (var source in sfxPool)
        {
            if (source.isPlaying)
            {
                source.Pause();
            }
        }
        
        if (sfxSource.isPlaying)
        {
            sfxSource.Pause();
        }
        
        if (uiSource.isPlaying)
        {
            uiSource.Pause();
        }
    }
    
    public void ResumeAllAudio()
    {
        musicSource.UnPause();
        
        foreach (var source in sfxPool)
        {
            source.UnPause();
        }
        
        sfxSource.UnPause();
        uiSource.UnPause();
    }
    
    // 公共方法：停止所有音频
    public void StopAllAudio()
    {
        StopMusic(false);
        
        foreach (var source in sfxPool)
        {
            source.Stop();
        }
        
        sfxSource.Stop();
        uiSource.Stop();
    }
    
    void OnValidate()
    {
        // 在编辑器中实时更新音量设置
        if (Application.isPlaying)
        {
            UpdateVolumeSettings();
        }
    }
    
    void OnDrawGizmos()
    {
        if (showDebugInfo)
        {
            // 绘制3D音效范围
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireSphere(transform.position, maxDistance);
            
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(transform.position, minDistance);
        }
    }
}